package com.test.work.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

public class SpringUtil implements ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(SpringUtil.class);
    private static ApplicationContext context;

    public SpringUtil() {
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        setStaticApplicationContext(context);
    }

    public static void setStaticApplicationContext(ApplicationContext context) {
        SpringUtil.context = context;
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (Exception var2) {
            Exception e = var2;
            log.debug("can not fetch the assign bean by class!", e);
            return null;
        }
    }

    /*public static <T> T getBean(String beanId) {
        try {
            return context.getBean(beanId);
        } catch (Exception var2) {
            Exception e = var2;
            log.debug("can not fetch the assign bean by beanId!", e);
            return null;
        }
    }*/

    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (clazz != null && null != beanName && !"".equals(beanName.trim())) {
            try {
                return context.getBean(beanName, clazz);
            } catch (Exception var3) {
                Exception e = var3;
                log.debug("can not fetch the assign bean by beanId!", e);
                return null;
            }
        } else {
            return null;
        }
    }

    public static ApplicationContext getContext() {
        return context == null ? null : context;
    }

    public static String getProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        String value = getProperty(key);
        return value != null ? value : defaultValue;
    }

    public static Integer getPropertyInteger(String key) {
        return (Integer)context.getEnvironment().getProperty(key, Integer.class);
    }

    public static Integer getPropertyInteger(String key, Integer defaultValue) {
        Integer value = getPropertyInteger(key);
        return value != null ? value : defaultValue;
    }

    public static void publishEvent(ApplicationEvent event) {
        if (context != null) {
            try {
                context.publishEvent(event);
            } catch (Exception var2) {
                Exception ex = var2;
                log.error(ex.getMessage());
            }

        }
    }
}
